//
//  TJSelectColorController.m
//  BaoDian
//
//  Created by mac on 2024/8/15.
//

#import "TJSelectColorController.h"
#import "TJButton.h"


@interface TJSelectColorController ()

@property (nonatomic, weak) UIView *contentView;
@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) TJButton *confirmButton;

@property (nonatomic, strong) UIView *colorView;
@property (nonatomic, strong) UIView *brightnessView;
@property (nonatomic, strong) UIView *colorSlider;
@property (nonatomic, strong) UIView *brightnessDot;
@property (nonatomic, assign) CGFloat sliderDiameter;
@property (nonatomic, strong) UIColor *selectedColor;
@property (nonatomic, assign) CGFloat brightness;

@end

@implementation TJSelectColorController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIButton *maskView = [[UIButton alloc] initWithFrame:self.view.bounds].addTo(self.view);
    maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    [maskView addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    _maskView = maskView;
    
    UIView *contentView = [UIView addToView:maskView];
    contentView.backgroundColor = UIColorMake(0x15161A);
    _contentView = contentView;
    
    UIView *titleView = [UIView addToView:contentView];
    [titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.height.offset(50);
    }];
    
    TJButton *cancelButton = [TJButton addToView:titleView];
    [cancelButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(didClickDismissButton) forControlEvents:UIControlEventTouchUpInside];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.height.width.offset(36);
        make.left.offset(10);
    }];
    
    TJButton *confirmButton = [TJButton addToView:titleView];
    [confirmButton setImage:[UIImage imageNamed:@"gou"] forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(didClickConfirmButton) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.height.width.offset(36);
        make.right.inset(10);
    }];
    
    CGFloat contentViewH = TabbarSafeBottomMargin + 245;
    contentView.frame = CGRectMake(0, KScreenHeight, KScreenWidth, contentViewH);
    [contentView addRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight radius:20];
    
    
    // 初始化默认值
    self.selectedColor = [UIColor colorWithHue:0 saturation:1 brightness:1 alpha:1];
    self.brightness = 1.0;
    
    // 创建颜色选择视图
    [self setupColorView];
    
    // 创建颜色滑块
    [self setupColorSlider];
    
    // 创建亮度选择视图
    [self setupBrightnessView];
    
    // 创建亮度圆点
    [self setupBrightnessDot];
}

- (void)setupColorView {
    self.colorView = [[UIView alloc] initWithFrame:CGRectMake(16, 50, KScreenWidth - 32, 10)];
    [self.contentView addSubview:self.colorView];
    self.colorView.layer.cornerRadius = self.colorView.bounds.size.height * 0.5;
    self.colorView.layer.masksToBounds = YES;
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.colorView.bounds;
    
    NSMutableArray *colors = [NSMutableArray array];
    NSMutableArray *locations = [NSMutableArray array];
    for (CGFloat hue = 0.0; hue <= 1.0; hue += 0.005) {
        [colors addObject:(id)[UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:1.0].CGColor];
        [locations addObject:@(hue)];
    }
    gradientLayer.colors = colors;
    gradientLayer.locations = locations;
    
    gradientLayer.startPoint = CGPointMake(0, 0.5);
    gradientLayer.endPoint = CGPointMake(1, 0.5);
    [self.colorView.layer addSublayer:gradientLayer];
}

- (void)setupColorSlider {
    CGFloat colorViewHeight = self.colorView.frame.size.height;
    self.sliderDiameter = colorViewHeight + 4;
    self.colorSlider = [[UIView alloc] initWithFrame:CGRectMake(self.colorView.frame.origin.x - self.sliderDiameter * 0.5, self.colorView.tj_y - 2, self.sliderDiameter, self.sliderDiameter)];
    self.colorSlider.backgroundColor = [UIColor whiteColor];
    self.colorSlider.layer.cornerRadius = self.sliderDiameter / 2;
    self.colorSlider.userInteractionEnabled = YES;
    [self.contentView addSubview:self.colorSlider];
    
    self.colorSlider.layer.shadowColor = [UIColor blackColor].CGColor; // 阴影颜色
     self.colorSlider.layer.shadowOffset = CGSizeMake(0, 2); // 阴影偏移量
     self.colorSlider.layer.shadowOpacity = 0.3; // 阴影透明度
     self.colorSlider.layer.shadowRadius = 4.0; // 阴影半径
    
    UIPanGestureRecognizer *colorPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleColorPan:)];
    [self.colorSlider addGestureRecognizer:colorPanGesture];
}

- (void)setupBrightnessView {
    self.brightnessView = [[UIView alloc] initWithFrame:CGRectMake(self.colorView.tj_x, 73, self.colorView.tj_width, 162)];
    [self.contentView addSubview:self.brightnessView];
    [self updateBrightnessView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleBrightnessTap:)];
    [self.brightnessView addGestureRecognizer:tapGesture];
}

- (void)setupBrightnessDot {
    
    CGFloat dotDiameter = 16;
    self.brightnessDot = [[UIView alloc] initWithFrame:CGRectMake(self.brightness * self.brightnessView.tj_width - dotDiameter / 2 - 100, self.brightnessView.tj_y + self.brightnessView.tj_height / 2 - dotDiameter / 2, dotDiameter, dotDiameter)];
    NSLog(@"self.brightnessDot = %@",  self.brightnessDot);
    self.brightnessDot.backgroundColor = [UIColor clearColor];
    self.brightnessDot.layer.borderColor = [UIColor whiteColor].CGColor;
    self.brightnessDot.layer.borderWidth = 2.0;
    self.brightnessDot.layer.cornerRadius = dotDiameter / 2;
    self.brightnessDot.userInteractionEnabled = YES;
    [self.contentView addSubview:self.brightnessDot];
    
    UIPanGestureRecognizer *brightnessPanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleBrightnessPan:)];
    [self.brightnessDot addGestureRecognizer:brightnessPanGesture];
}

- (void)handleColorPan:(UIPanGestureRecognizer *)gesture {
    CGPoint translation = [gesture translationInView:self.contentView];
    CGPoint newCenter = CGPointMake(gesture.view.center.x + translation.x, self.colorView.center.y);
    
    newCenter.x = MAX(self.colorView.frame.origin.x, newCenter.x);
    newCenter.x = MIN(self.colorView.frame.origin.x + self.colorView.frame.size.width, newCenter.x);
    
    gesture.view.center = newCenter;
    [gesture setTranslation:CGPointZero inView:self.view];
    
    CGFloat percentage = (gesture.view.center.x - self.colorView.frame.origin.x) / self.colorView.frame.size.width;
    self.selectedColor = [self colorAtPercentage:percentage];
    [self updateBrightnessView];
    [self updateLabelColor];
}

- (void)handleBrightnessPan:(UIPanGestureRecognizer *)gesture {
    CGPoint translation = [gesture translationInView:self.contentView];
    CGPoint newCenter = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y + translation.y);
    
    newCenter.x = MAX(self.brightnessView.frame.origin.x, newCenter.x);
    newCenter.x = MIN(self.brightnessView.frame.origin.x + self.brightnessView.frame.size.width, newCenter.x);
    
    newCenter.y = MAX(self.brightnessView.frame.origin.y, newCenter.y);
    newCenter.y = MIN(self.brightnessView.frame.origin.y + self.brightnessView.frame.size.height, newCenter.y);
    
    gesture.view.center = newCenter;
    [gesture setTranslation:CGPointZero inView:self.view];
    
    CGFloat xPercentage = (gesture.view.center.x - self.brightnessView.frame.origin.x) / self.brightnessView.frame.size.width;
    CGFloat yPercentage = 1.0 - (gesture.view.center.y - self.brightnessView.frame.origin.y) / self.brightnessView.frame.size.height;
    self.brightness = yPercentage;
    
    // 确保视图更新
    [self.contentView layoutIfNeeded];
    
    // 获取滑块中心点在亮度视图中的颜色
    CGPoint brightnessDotCenterInView = CGPointMake(self.brightnessDot.center.x - self.brightnessView.frame.origin.x,
                                                    self.brightnessDot.center.y - self.brightnessView.frame.origin.y);
    
    UIColor *clickedColor = [self colorAtView:self.brightnessView point:brightnessDotCenterInView];

    if (clickedColor) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.selecteComplete) {
                self.selecteComplete(clickedColor);
            }
        });
    }
    
}


- (void)handleBrightnessTap:(UITapGestureRecognizer *)gesture {
    CGPoint location = [gesture locationInView:self.brightnessView];
    
    // 计算点击点的亮度
    CGFloat xPercentage = location.x / self.brightnessView.frame.size.width;
    CGFloat yPercentage = 1.0 - (location.y / self.brightnessView.frame.size.height);
    self.brightness = yPercentage;
    
    // 更新亮度圆点的位置
    self.brightnessDot.center = CGPointMake(location.x + self.brightnessView.frame.origin.x, location.y + self.brightnessView.frame.origin.y);
    
    // 获取点击点的颜色
    UIColor *clickedColor = [self colorAtView:self.brightnessView point:location];
    
    // 更新Label的颜色
    if (clickedColor) {
        if (self.selecteComplete) {
            self.selecteComplete(clickedColor);
        }
    }
    
}

 

- (UIColor *)colorAtView:(UIView *)view point:(CGPoint)point {
    
    if (!CGRectContainsPoint(view.bounds, point)) {
          return nil;
    }
    
    unsigned char pixel[4] = {0};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pixel, 1, 1, 8, 4, colorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedLast);

    CGContextTranslateCTM(context, -point.x, -point.y);

    [view.layer renderInContext:context];

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);

    UIColor *color = [UIColor colorWithRed:pixel[0]/255.0 green:pixel[1]/255.0 blue:pixel[2]/255.0 alpha:pixel[3]/255.0];

    return color;
}
 

- (UIColor *)colorAtPercentage:(CGFloat)percentage {
    CGFloat hue = percentage;
    return [UIColor colorWithHue:hue saturation:1.0 brightness:1.0 alpha:1.0];
}

- (UIColor *)color:(UIColor *)color withBrightnessPercentage:(CGFloat)percentage {
    CGFloat hue, saturation, brightness, alpha;
    [color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    brightness = percentage;
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
}

- (void)updateBrightnessView {
    // 创建一个新的渐变层
    CAGradientLayer *brightnessGradientLayer = [CAGradientLayer layer];
    brightnessGradientLayer.frame = self.brightnessView.bounds;
    
    // 获取当前颜色在不同亮度下的颜色
    UIColor *highBrightnessColor = [self color:self.selectedColor withBrightnessPercentage:1.0];
    UIColor *lowBrightnessColor = [self color:self.selectedColor withBrightnessPercentage:0.0];
    
    // 加入白色作为渐变的一部分
    UIColor *whiteColor = [UIColor whiteColor];
    
    // 设置渐变的颜色数组和位置数组
    brightnessGradientLayer.colors = @[
        (id)highBrightnessColor.CGColor,
         (id)lowBrightnessColor.CGColor,
     ];
    
    // 设置渐变的起始点和结束点
    
    brightnessGradientLayer.startPoint = CGPointMake(0, 0);
    brightnessGradientLayer.endPoint = CGPointMake(1, 1); // 水平渐变
    
    // 移除之前的子图层
    [self.brightnessView.layer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    
    // 添加新的渐变图层
    [self.brightnessView.layer addSublayer:brightnessGradientLayer];
    
    // 更新亮度圆点的位置
    CGFloat dotDiameter = self.brightnessDot.frame.size.width;
    self.brightnessDot.center = CGPointMake(self.brightnessView.frame.origin.x + self.brightness * self.brightnessView.frame.size.width, self.brightnessView.frame.origin.y + (1 - self.brightness) * self.brightnessView.frame.size.height);
}



- (void)updateLabelColor {
    UIColor *color = [self color:self.selectedColor withBrightnessPercentage:self.brightness];
    if (self.selecteComplete) {
        self.selecteComplete(color);
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    _confirmButton.enabled = !isEmptyString(textField.text);
}
 
- (void)didClickConfirmButton {
    [self dismissComplete:nil];
}
 
- (void)didClickDismissButton {
    [self dismissComplete:nil];
}

- (void)didClickMaskButton {
    [self.view endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.tj_y = KScreenHeight - self.contentView.tj_height;
    } completion:^(BOOL finished) {
    }];
    
}

- (void)dismissComplete:(void (^)(void))complete {
    [UIView animateWithDuration:0.25 animations:^{
        self.contentView.tj_y = KScreenHeight;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) {
                complete();
            }
        }];
    }];
}

- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationCustom;
}


@end
